package com.dep.base;

import com.dep.util.StringUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class BaseController {

	@Resource
	protected HttpServletRequest req;
	@Resource
	protected HttpServletResponse resp;




	protected String getAttribute(){
		return getAttributeToStr("infoId");
	}
	protected String getAttributeForLoginId(){
		return getAttributeToStr("loginId");
	}

	protected String getAttributeForIp() {
        String ipAddress = null;
		if(!StringUtil.isNullorEmpty(req.getAttribute("ip"))){
			ipAddress = req.getAttribute("ip").toString();
		}
		return ipAddress;
	}

	protected String getAttributeToStr(String key){
		Object value = req.getAttribute(key);
		if(StringUtil.isNullorEmpty(value)){
			return null;
		}
		return value.toString();
	}

	protected String getHeaderToStr(String key){
		return req.getHeader(key);
	}

	protected String getPara(String key) {
		return req.getParameter(key);
	}

	protected Byte getParaToByte(String key) {
		String value = req.getParameter(key);
		return value != null ? Byte.valueOf(value) : null;
	}

	protected Short getParaToShort(String key) {
		String value = req.getParameter(key);
		return value != null ? Short.valueOf(value) : null;
	}

	protected Integer getParaToInt(String key) {
		String value = req.getParameter(key);
		return value != null ? Integer.valueOf(value) : null;
	}

	protected Long getParaToLong(String key) {
		String value = req.getParameter(key);
		return value != null ? Long.valueOf(value) : null;
	}

	protected String getAttrToStr(String key) {
		Object value = req.getAttribute(key);
		return (String) value;
	}

	protected Byte getAttrToByte(String key) {
		Object value = req.getAttribute(key);
		return (Byte) value;
	}

	protected Short getAttrToShort(String key) {
		Object value = req.getAttribute(key);
		return (Short) value;
	}

	protected Integer getAttrToInt(String key) {
		Object value = req.getAttribute(key);
		return (Integer) value;
	}

	protected Long getAttrToLong(String key) {
		Object value = req.getAttribute(key);
		return (Long) value;
	}
	protected Map<String,String> getAllParameter() {

		Map<String, String> map = new HashMap<>();
		Enumeration enums = req.getParameterNames();
		while (enums.hasMoreElements()) {
			String paramName = (String) enums.nextElement();

			String paramValue = req.getParameter(paramName);
			//形成键值对应的map
			map.put(paramName, paramValue);
		}
		return map;
	}
}
